package com.xayy.health.ds.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.kawins.base.result.CheckResult;
import cn.kawins.base.utils.BeanUtil;
import cn.kawins.base.utils.CollUtil;
import cn.kawins.base.utils.StringUtil;
import com.xayy.health.core.config.param.ModelFaultParams;
import com.xayy.health.core.enums.ModelTrainStatusEnum;
import com.xayy.health.ds.model.*;
import com.xayy.health.ds.service.DsModelAlgorithmInfoService;
import com.xayy.health.ds.service.DsModelTrainAccuracyService;
import com.xayy.health.mgt.model.dto.ModelDto;
import com.xtck.ha.common.core.domain.R;
import com.xtck.ha.common.core.web.service.dsimpl.BaseServiceImpl;
import com.xtck.ha.common.core.config.DsServerConfig;
import com.xtck.ha.common.core.utils.DomainUtils;
import com.xayy.health.ds.service.DsModelTrainRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @Description: DsModelTrainRecordService实现类
 * @Auther:liuyuan
 * @Date:2025-07-08
 */
@Slf4j
@Service
public class DsModelTrainRecordServiceImpl extends BaseServiceImpl<DsModelTrainRecord> implements DsModelTrainRecordService {
  /**
  *
  * 冗余代码，为自定义开发DS-Server接口服务
  *
  */
   private static String TABLE_NAME = "TB_MODEL_TRAIN_RECORD";
   private String getUrl(){
      return getDsServerConfig().getUrl();
   }
   @Autowired
    DsModelTrainAccuracyService dsModelTrainAccuracyService;
   @Autowired
    DsModelAlgorithmInfoService dsModelAlgorithmInfoService;

    /**
     * 获取模型准确度
     *
     * @param modelTrainRecord 模型训练记录
     * @return ResultBody
     */
    @Override
    public CheckResult<Object> selectInfo(DsModelTrainRecord modelTrainRecord) {
        DsModelInfoVo modelInfoVo = new DsModelInfoVo();
        String modelId = modelTrainRecord.getId();
        DsModelTrainRecord info = selectTById(modelId);
        String sql = "select * from HEALTH.tb_model_train_accuracy t where t.model_train_record_id = " +
                " '" + modelId + "'" +
                " order by time asc";
        List<DsModelTrainAccuracy> result = dsModelTrainAccuracyService.selectBySql(sql);
//        if(!CollectionUtils.isEmpty(result)){
//            result=addDataToList(result);
//
//        }
        modelInfoVo.setTestModel(result);

        List<DsModelAlgorithmInfo> select =
                dsModelAlgorithmInfoService.selectTList(DsModelAlgorithmInfo.builder().modelId(modelId).build());

        List<DsAlgorithmParams> algorithmParamList = new ArrayList<>();
        if (CollUtil.isNotEmpty(select)) {
            select.forEach(x -> algorithmParamList.add(BeanUtil.copyBean(x, DsAlgorithmParams.class)));
        }

        if (info.getModelType() == 1) {
            // cnn
            DsCalculateModelTrain calculateModelTrain = BeanUtil.copyBean(info, DsCalculateModelTrain.class);
            calculateModelTrain.setAlgorithmParamList(algorithmParamList);
            modelInfoVo.setCalculateModelTrain(calculateModelTrain);
            calculateModelTrain.setModelName(info.getId());
        } else {
            // lstm
            DsModelTrain modelTrain = BeanUtil.copyBean(info, DsModelTrain.class);
            modelTrain.setAlgorithmParamList(algorithmParamList);
            modelTrain.setModelName(modelTrainRecord.getId());
            List<ModelFaultParams> dates = new ArrayList<>();
            String errorStart = info.getErrorStart();
            String errorEnd = info.getErrorEnd();
            if (StringUtil.isNotBlank(errorStart) && StringUtil.isNotBlank(errorEnd)) {
                String[] splitS = errorStart.split(",");
                String[] splitE = errorEnd.split(",");
                if (splitS.length == splitE.length) {
                    for (int i = 0; i < splitS.length; i++) {
                        DateTime parseS = DateUtil.parse(splitS[i], "yyyy-MM-dd HH:mm:ss");
                        DateTime parseE = DateUtil.parse(splitE[i], "yyyy-MM-dd HH:mm:ss");
                        ModelFaultParams modelFaultParams = new ModelFaultParams();
                        modelFaultParams.setErrorStart(parseS);
                        modelFaultParams.setErrorEnd(parseE);
                        dates.add(modelFaultParams);
                    }
                }

            }
            modelTrain.setDates(dates);
            modelInfoVo.setModelTrain(modelTrain);
        }
        return CheckResult.success(modelInfoVo);
    }

    /**
     * 校验模型名称是否重复
     *
     * @param modelTrain 入参信息
     * @return 结果日志
     */
    @Override
    public CheckResult<Object> checkModelName(DsCalculateModelTrain modelTrain) {
        DsModelTrainRecord selectBody = DsModelTrainRecord.builder()
                .satelliteCode(modelTrain.getSatelliteCode())
                .paramCode(modelTrain.getParamCode())
                .modelType(modelTrain.getModelType())
                .modelName(modelTrain.getModelName())
                .build();
        List<DsModelTrainRecord> modelTrainRecords = selectTList(selectBody);
        if (CollUtil.isNotEmpty(modelTrainRecords)) {
            return CheckResult.fail("模型名称：" + modelTrain.getModelName() + "已存在！");
        }
        return CheckResult.success();
    }

    /**
     * 删除模型任务
     *
     * @param modelTypeId 模型任务id
     * @return ResultBody
     */
    @Override
    public CheckResult<Object> deleteModelTaskById(Long modelTypeId) {
        DsModelTrainRecord modelTrainRecord = selectTList(DsModelTrainRecord.builder().id(modelTypeId.toString()).build()).get(0);
        deleteTById(modelTypeId);
        DsModelTrainAccuracy deleteBody = DsModelTrainAccuracy.builder().modelTrainRecordId(modelTypeId.toString()).build();
        dsModelTrainAccuracyService.deleteTList(deleteBody);
        return CheckResult.success("模型" + modelTrainRecord.getModelName() + "删除成功");
    }

    /**
     * 模型下拉列表
     * @param modelDto 入参
     * @return ResultBody
     */
    @Override
    public CheckResult<Object> getModel(ModelDto modelDto) {
        List<DsModelTrainRecord> list = CollUtil.newArrayList();
        List<DsModelTrainRecord> modelTrainRecords = null;
        DsModelTrainRecord modelTrainRecord = DsModelTrainRecord.builder().modelType(modelDto.getModelType()).satelliteCode(modelDto.getSatelliteCode()).status(ModelTrainStatusEnum.DONE.getCode()).build();
        DsModelTrainRecord modelTrainRecordAndParamCode = DsModelTrainRecord.builder().modelType(modelDto.getModelType()).satelliteCode(modelDto.getSatelliteCode()).paramCode(modelDto.getParamCode()).status(ModelTrainStatusEnum.DONE.getCode()).build();
        //isCurrentParams 0 匹配 1不匹配
        if (modelDto.getIsCurrentParams() == 1) {
            modelTrainRecords = selectTList(modelTrainRecordAndParamCode);
        } else {
            modelTrainRecords = selectTList(modelTrainRecord);
        }
        list.addAll(modelTrainRecords);
        return CheckResult.success(list);
    }
}
